package org.mesh4j.sync.adapters.feed.rss;

import java.io.Writer;
import java.util.Date;

import org.kxml2.kdom.Document;
import org.kxml2.kdom.Element;
import org.mesh4j.sync.adapters.feed.ISyndicationFormat;
import org.mesh4j.sync.utils.DateHelper;

public class RssSyndicationFormat implements ISyndicationFormat {

	public static final String RSS_ELEMENT_ROOT = "rss";
	public static final String RSS_ELEMENT_ITEM = "item";
	public static final String RSS_ELEMENT_CHANNEL = "channel";
	public static final RssSyndicationFormat INSTANCE = new RssSyndicationFormat();

	public Element getBaseElement(Document document) {
		Element channel = document.getRootElement().getElement(null, RSS_ELEMENT_CHANNEL);
		return channel;
	}

	public boolean isFeedItem(Element element) {
		return RSS_ELEMENT_ITEM.equals(element.getName());
	}

	public Date parseDate(String dateAsString) {
		return dateAsString == null ? null : DateHelper.parseRFC822(dateAsString);
	}
	
	public String formatDate(Date date) {
		return date == null ? "" : DateHelper.formatRFC822(date);
	}

	public Element addRootElement(Document document) {
		Element rootElement = new Element();
		rootElement.setName(RSS_ELEMENT_ROOT);
		rootElement.setAttribute(null, "version", "2.0");
		rootElement.setPrefix(SX_PREFIX, NAMESPACE);
		document.addChild(Element.ELEMENT, rootElement);
		
		Element channel = new Element();
		channel.setName(RSS_ELEMENT_CHANNEL);
		rootElement.addChild(Element.ELEMENT, channel);
		return channel;
	}

	public Element addFeedItemElement(Element root) {
		Element item = new Element();
		item.setName(RSS_ELEMENT_ITEM);
		root.addChild(Element.ELEMENT, item);
		return item;
	}
	
	public void writeStartDocument(Writer writer) throws Exception {
		writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		writer.write("<rss version=\"2.0\" xmlns:sx=\"http://feedsync.org/2007/feedsync\">");
		writer.write("<channel>");		
	}
	
	public void writeEndDocument(Writer writer) throws Exception {
		writer.write("</channel>");
		writer.write("</rss>");		
	}

	public void writeEndItem(Writer writer) throws Exception {
		writer.write("</item>");		
	}

	public void writeStartItem(Writer writer) throws Exception {
		writer.write("<item>");		
	}

	public String getName() {
		return "RSS";
	}

}
